package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClient fastDFSClient;

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadPic(MultipartFile file) {
        /**
         * 1:校验参数
         * 2：fastdfs工具类 执行上传文件
         * 3：把上传好的图片进行地址拼接 返回前端   能正常回显图片
         */
        if(file==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        try {
            String filePath = fastDFSClient.uploadFile(file);

            //获取当前登录用户
            WmUser wmUser = WmThreadLocalUtils.getUser();
            Integer userId =null;
            if(wmUser!=null){
                userId=wmUser.getId();
            }

            //保存素材数据 wm mateical
            WmMaterial wmMaterial =new WmMaterial();
            wmMaterial.setUrl(filePath);
            wmMaterial.setUserId(userId);
            wmMaterial.setIsCollection((short)0); //0:不收藏 1；收藏
            wmMaterial.setType((short)0);
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);


            //group1/M00/12/22/XXXXXX.jpg -->  http://192.168.58.138/group1/M00/12/22/XXXXXX.jpg
            wmMaterial.setUrl(fileServerUrl +filePath);
            return ResponseResult.okResult(wmMaterial);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public ResponseResult list(WmMaterialDto dto) {
        /**
         * 1:参数校验danqian
         * 2：分页查询  当前登录用户  收藏 1 收藏
         * 3: 封装数据 拼接服务器ip地址  回显图片
         */

        if(dto==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper =new LambdaQueryWrapper<>();

        //获取当前登录用户
        WmUser wmUser = WmThreadLocalUtils.getUser();
        Integer userId =null;
        if(wmUser!=null){
            userId=wmUser.getId();
        }

        lambdaQueryWrapper.eq(WmMaterial::getUserId,userId);
        //1 收藏 0 全部
        if(dto.getIsCollection()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);


        Page page = new Page(dto.getPage(),dto.getSize());
        IPage result =this.page(page,lambdaQueryWrapper);

        ResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getSize(),(int)result.getTotal());


        //stream流 重新更新集合内容
        List<WmMaterial> records = result.getRecords();
        records = records.stream().map(w->{
            w.setUrl(fileServerUrl +w.getUrl());
            return w;
        }).collect(Collectors.toList());

        responseResult.setData(records);

        return responseResult;
    }

    @Override
    public ResponseResult delPic(Integer id) {

        /**
         * 1:校验参数
         * 2：判断是否有引用
         * 3：删 fastdfs 图片   删数据库素材数据
         *
         */
        if(id==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNewsMaterial::getMaterialId,id);

        Integer count = wmNewsMaterialMapper.selectCount(lambdaQueryWrapper);

        if(count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        //删除  fastdfs 图片
        WmMaterial wmMaterial = this.getById(id);
        String newUrl = wmMaterial.getUrl().replace(fileServerUrl, "");
        fastDFSClient.delFile(newUrl);
        //删数据 物理删除
        this.removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.更新状态
        WmUser wmUser = WmThreadLocalUtils.getUser();
        Integer userId =null;
        if(wmUser!=null){
            userId=wmUser.getId();
        }
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
